package com.cropflow.controller;

import com.cropflow.entity.MaintenanceRecord;
import com.cropflow.entity.Vehicle;
import com.cropflow.service.MaintenanceService;
import com.cropflow.service.VehicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/vehicles")
public class VehicleController {

    @Autowired
    private VehicleService vehicleService;

    @Autowired
    private MaintenanceService maintenanceService;

    // 设备列表页面
    @GetMapping
    public String listVehicles(Model model) {
        List<Vehicle> vehicles = vehicleService.getAllVehicles();
        model.addAttribute("vehicles", vehicles);
        model.addAttribute("statusOptions", Vehicle.VehicleStatus.values());
        return "vehicles/list";
    }

    // 设备详情页面
    @GetMapping("/{id}")
    public String vehicleDetail(@PathVariable Long id, Model model) {
        Vehicle vehicle = vehicleService.getVehicleById(id);
        List<MaintenanceRecord> maintenanceRecords = maintenanceService.getMaintenanceRecordsByVehicleId(id);

        model.addAttribute("vehicle", vehicle);
        model.addAttribute("maintenanceRecords", maintenanceRecords);
        return "vehicles/detail";
    }

    // 添加设备页面
    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("vehicle", new Vehicle());
        model.addAttribute("statusOptions", Vehicle.VehicleStatus.values());
        return "vehicles/add";
    }

    // 保存新设备
    @PostMapping("/add")
    public String addVehicle(@ModelAttribute Vehicle vehicle) {
        vehicleService.saveVehicle(vehicle);
        return "redirect:/vehicles";
    }

    // 编辑设备页面
    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Long id, Model model) {
        Vehicle vehicle = vehicleService.getVehicleById(id);
        model.addAttribute("vehicle", vehicle);
        model.addAttribute("statusOptions", Vehicle.VehicleStatus.values());
        return "vehicles/edit";
    }

    // 更新设备
    @PostMapping("/edit/{id}")
    public String updateVehicle(@PathVariable Long id, @ModelAttribute Vehicle vehicle) {
        vehicle.setId(id);
        vehicleService.saveVehicle(vehicle);
        return "redirect:/vehicles";
    }

    // 删除设备
    @GetMapping("/delete/{id}")
    public String deleteVehicle(@PathVariable Long id) {
        vehicleService.deleteVehicle(id);
        return "redirect:/vehicles";
    }

    // 维护记录页面
    @GetMapping("/{id}/maintenance")
    public String maintenanceRecords(@PathVariable Long id, Model model) {
        Vehicle vehicle = vehicleService.getVehicleById(id);
        List<MaintenanceRecord> records = maintenanceService.getMaintenanceRecordsByVehicleId(id);

        model.addAttribute("vehicle", vehicle);
        model.addAttribute("maintenanceRecords", records);
        model.addAttribute("newRecord", new MaintenanceRecord());
        model.addAttribute("maintenanceTypes", MaintenanceRecord.MaintenanceType.values());
        return "vehicles/maintenance";
    }

    // 添加维护记录
    @PostMapping("/{id}/maintenance")
    public String addMaintenanceRecord(@PathVariable Long id, @ModelAttribute MaintenanceRecord record) {
        Vehicle vehicle = vehicleService.getVehicleById(id);
        record.setVehicle(vehicle);
        maintenanceService.saveMaintenanceRecord(record);
        return "redirect:/vehicles/" + id + "/maintenance";
    }

    // 远程控制页面
    @GetMapping("/{id}/control")
    public String remoteControl(@PathVariable Long id, Model model) {
        Vehicle vehicle = vehicleService.getVehicleById(id);
        model.addAttribute("vehicle", vehicle);
        return "vehicles/control";
    }

    // REST API接口
    @RestController
    @RequestMapping("/api/vehicles")
    public static class VehicleRestController {

        @Autowired
        private VehicleService vehicleService;

        @Autowired
        private MaintenanceService maintenanceService;

        // 获取所有设备
        @GetMapping
        public List<Vehicle> getAllVehicles() {
            return vehicleService.getAllVehicles();
        }

        // 设备状态API
        @GetMapping("/{id}/status")
        public ResponseEntity<Map<String, Object>> getVehicleStatus(@PathVariable Long id) {
            Vehicle vehicle = vehicleService.getVehicleById(id);
            if (vehicle != null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("status", vehicle.getStatus());
                response.put("battery", 85); // 模拟电量
                response.put("speed", 12.5); // 模拟速度
                response.put("fuel", 78);    // 模拟油量
                response.put("load", 45);    // 模拟负载
                return ResponseEntity.ok(response);
            }
            return ResponseEntity.notFound().build();
        }

        // 更新设备位置
        @PostMapping("/{id}/location")
        public ResponseEntity<String> updateLocation(@PathVariable Long id,
                                                     @RequestParam Double latitude,
                                                     @RequestParam Double longitude) {
            vehicleService.updateVehicleLocation(id, latitude, longitude);
            return ResponseEntity.ok("Location updated successfully");
        }

        // 发送控制指令
        @PostMapping("/{id}/control")
        public ResponseEntity<String> sendControlCommand(@PathVariable Long id, @RequestBody Map<String, String> command) {
            boolean success = vehicleService.sendControlCommand(id, command.get("command"));
            String result = success ? "Command executed successfully" : "Command execution failed";
            return ResponseEntity.ok(result);
        }

        // 更新设备配置
        @PostMapping("/{id}/config")
        public ResponseEntity<String> updateConfig(@PathVariable Long id, @RequestBody Map<String, Object> config) {
            boolean success = vehicleService.updateVehicleConfig(id, config);
            String result = success ? "Configuration updated successfully" : "Configuration update failed";
            return ResponseEntity.ok(result);
        }

        // 获取维护记录
        @GetMapping("/{id}/maintenance")
        public List<MaintenanceRecord> getMaintenanceRecords(@PathVariable Long id) {
            return maintenanceService.getMaintenanceRecordsByVehicleId(id);
        }
    }
}